/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.metadata.schemasutilities;

import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;

import uk.ljmu.metadata.utilities.MetadataUtilities;

public class GeoUtilities {
	private static final Logger log = Logger.getLogger(GeoUtilities.class);
	/**
	 * 
	 * @param prefixList
	 * @param aboutID
	 * 
	 * @return Document
	 */
	public static Document createEmptyGeoRecord(List<String> prefixList, String aboutID)
	{
		Element root = DocumentHelper.createElement( "rdf:RDF" );
		root.addNamespace("rdf", MetadataUtilities.RELS_MAP.get("rdf"));
		root.addNamespace("rdfs", MetadataUtilities.RELS_MAP.get("rdfs"));
		root.addNamespace("geo", MetadataUtilities.MDSchemasUrl.get("geo"));

		if (prefixList != null && prefixList.size() > 0)
		{
			for (String pref : prefixList)
			{
				String ns = MetadataUtilities.MDSchemasUrl.get(pref);
				if (ns == null)
					continue;
				root.addNamespace(pref, ns);
			}
		}
		/*
		 * <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
  			<geo:Point>
    			<geo:lat>55.701</geo:lat>
    			<geo:long>12.552</geo:long>
  			</geo:Point>
		</rdf:RDF>
		 * */
		//Create document
		Element description = DocumentHelper.createElement("rdf:Description");
		description.addAttribute("rdf:about", !aboutID.startsWith("info") ? MetadataUtilities.OBJECTID + aboutID : aboutID);
		root.add(description);
		Document doc = DocumentHelper.createDocument(root);


		return doc;
	}
	/**
	 * 
	 * @param xmlContents
	 * @param prefixList
	 * @param aboutID
	 * 
	 * @return Document
	 * @throws Exception 
	 */
	public static Document createEmptyGeoRecordAllInOne(String xmlContents, List<String> prefixList, String aboutID) throws Exception
	{
		if (xmlContents.equals("")) {
			Document doc = GeoUtilities.createEmptyGeoRecord(prefixList, aboutID);
			return doc;
		}
		else {
			//Create document
			Document doc = null;
				
			try 
			{
				doc = DocumentHelper.parseText(xmlContents);
			} catch (DocumentException e) {
				log.fatal(e.getMessage());
			}
			if (doc != null) {
				Element root = doc.getRootElement();
				if (prefixList != null && prefixList.size() > 0)
				{
					for (String pref : prefixList)
					{
						String ns = MetadataUtilities.MDSchemasUrl.get(pref);
						if (ns == null)
							continue;
						root.addNamespace(pref, ns);
					}
				}
				Element description = DocumentHelper.createElement("rdf:Description");
				description.addAttribute("rdf:about", !aboutID.startsWith("info") ? MetadataUtilities.OBJECTID + aboutID : aboutID);
				root.add(description);

				return doc;	
			}
			else {
				//ERROR creating RDF document
				log.fatal("Error while creating RDF-GEO Document");
				throw new Exception("createEmptyGeoRecordAllInOne, error while creatin RDF document");
			}
		}
	}
	/**
	 * Add a property to an existing RDF description record
	 * 
	 * @param propertyName string with the property name
	 * @param propertyValue string with the value of the property
	 * @param xmlContents String containing the actual record in which to add the new property
	 * 
	 * @return Document with the properties added
	 */
	public static Document addGeoProperty(String propertyName, String propertyValue, String xmlContents)
	{
		//Create document
		Document doc = null;
		try 
		{
			doc = DocumentHelper.parseText(xmlContents);
		} catch (DocumentException e) {
			log.fatal(e.getMessage());
		}
		if (doc != null)
		{
			Element root = doc.getRootElement();
			Element desc = root.element("Description");
			Namespace ns = new Namespace("geo", MetadataUtilities.MDSchemasUrl.get("geo"));
			QName qname;
			
			//Already Qualified
			if (!propertyName.contains(":"))
				qname = new QName(propertyName, ns);
			else qname = new QName(propertyName);
			Element property = DocumentHelper.createElement(qname);
			property.setText(propertyValue);
			desc.add(property);

			return doc;
		} 
		else
		{
			log.info("Error while creating RDF-GEO Document");
			return null;
		}
	}
}
